package com.gridmobi.xrtb.saveclick;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gridmobi.xrtb.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * RTB实时数据更新 以及reindex
 *
 * @author huangyongchao
 */
@Component
public class CounterClickJob {


    private static final Logger logger = LoggerFactory.getLogger(CounterClickJob.class);

    @Value("${url.recordclicks}")
    private String recordclicksUrl;

    @Autowired
    private RestTemplate restTemplate;


    @Scheduled(cron = "0 */5 *  * * ?")
    public void sendClicks() {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<Integer, Map<Integer, Map<String, CntClick>>> oldMap = CounterClickHandler.CURRENT_CLICKS;
            CounterClickHandler.CURRENT_CLICKS = Maps.newConcurrentMap();
            try {
                List<CounterClickDto> list = Lists.newLinkedList();
                oldMap.forEach((oid, om) -> {
                    om.forEach((hour, hm) -> {
                        hm.forEach((sub, cnt) -> {
                            CounterClickDto dto = new CounterClickDto();
                            dto.setOid(oid);
                            dto.setDate(DateTimeUtil.getStringDateShort());
                            dto.setPid(1);
                            dto.setPubsub(sub);
                            dto.setUtchour(hour);
                            dto.setAmount(cnt.getClicks().get());
                            dto.setErramount(cnt.getErrclicks().get());
                            list.add(dto);
                        });
                    });

                });
                HttpEntity entity = new HttpEntity(list);
                logger.warn(JSONObject.toJSONString(list));
                restTemplate.exchange(recordclicksUrl, HttpMethod.POST, entity, String.class);
            } catch (RestClientException e) {
                e.printStackTrace();
                CounterClickHandler.CURRENT_CLICKS = oldMap;
            }

        } catch (RestClientException e) {
            e.printStackTrace();

        }

    }
}
